package com.xinshujia.config.authorization;

import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.function.Supplier;

/**
 * @author: 野狼上校
 * @create: 2023-05-30  22:32
 * @version: 1.0
 * @description: 授权决策管理器
 */
@Component
public class MyAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> {
    private final MySecurityMetadataSource mySecurityMetadataSource;

    public MyAuthorizationManager(MySecurityMetadataSource mySecurityMetadataSource) {
        this.mySecurityMetadataSource = mySecurityMetadataSource;
    }

    @Override
    public void verify(Supplier<Authentication> authentication, RequestAuthorizationContext object) {
        AuthorizationManager.super.verify(authentication, object);
    }

    @Override
    public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext context) {
        // 测试使用 （都放行）
        return new AuthorizationDecision(true);
//        return getAuthorizationDecision(authentication, context);
    }

    /**
     * 实际使用
     */
    private AuthorizationDecision getAuthorizationDecision(Supplier<Authentication> authentication, RequestAuthorizationContext context) {
        //1. 获取认证成功的用户拥有的角色
//        Collection<? extends GrantedAuthority> authorities = authentication.get().getAuthorities();

        //2. 访问的URI
        String requestURI = context.getRequest().getRequestURI();

        // 3. 能够访问的资源
        Set<String> resourceUris = mySecurityMetadataSource.getResourceUris();
        if(resourceUris.isEmpty()) return new AuthorizationDecision(false);

        if (resourceUris.contains(requestURI)) {
            // 授权成功
            return new AuthorizationDecision(true);
        }
        // 授权失败
        return new AuthorizationDecision(false);
    }
}
